<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;

/**
 * 用户管理控制器
 * Class User
 * @package app\community\controller
 * @author zoudingyong <sheyingtg@qq.com>
 * @date 2018/11/2 13:12
 */
class Member extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $member = 'tp_member';

    /**
     * 用户列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '用户管理';
        $get = $this->request->get();
        $db = Db::name($this->member)
            ->alias('a')
            ->field('a.*');

        foreach (['id', 'name', 'mobile', 'company'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.' . $key, "%{$get[$key]}%");
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        $db->where([]);
        return parent::_list($db->order('a.id desc'));
    }


    /**
     * 添加
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->title = '添加';
            return $this->_form($this->member, 'form');
        }
        try {
            $data = $this->request->post();
            Db::transaction(function () use ($data) {

                $haveMember = Db::name($this->member)->where(['mobile' => $data['mobile']])->find();
                if ($haveMember) {
                    $this->error('添加失败，手机号已存在！');
                }
                $data['password'] = md5('123456');
                $id = Db::name($this->member)->insertGetId($data);

                $member = Db::name($this->member)->where(['id' => $id])->find();
                Cache::store('redis')->handler()->hMset('member:mobile:' . $member['mobile'], $member);
            });


        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('添加失败，请稍候再试！');
        }
        $this->success('添加成功！', "");
    }


    /**
     * 编辑
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $info = Db::name($this->member)->where(['id' => $id])->find();
            empty($info) && $this->error('需要编辑的用户不存在！');
            return $this->fetch('form', ['vo' => $info, 'title' => '编辑']);
        }
        try {
            $data = $this->request->post();
            $id = $this->request->post('id');
            $info = Db::name($this->member)->where(['id' => $id])->find();
            empty($info) && $this->error('编辑失败，请稍候再试！');

            Db::transaction(function () use ($data, $id, $info) {
                // 更新产品主表
                $where = ['id' => $id];
                Db::name($this->member)->where($where)->update([
                    'name' => $data['name'],
                    'mobile' => $data['mobile'],
//                    'password' => md5($data['password']),
                ]);

            });
            Cache::store('redis')->handler()->del('member:mobile:' . $info['mobile']);
            $member = Db::name($this->member)->where(['id' => $id])->find();
            Cache::store('redis')->handler()->hMset('member:mobile:' . $member['mobile'], $member);

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑作品失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('member/index')];
        $this->success('编辑成功！', "{$base}#{$url}?spm={$spm}");
    }


    /**
     * 删除用户
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        $member_ids = $this->request->post('id');
        $member_ids = explode(',', $member_ids);
        foreach ($member_ids as $member_id) {
            $member = Db::name($this->member)->where(['id' => $member_id])->find();
            Cache::store('redis')->handler()->del('member:mobile:' . $member['mobile']);
            Db::name($this->member)->where('id', $member_id)->delete();
        }

        $this->success("用户删除成功！", '');
    }
}
